<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px">
      <el-row>

        <el-form-item label="分类名称" prop="groupName">
          <el-input v-model="queryParams.groupName" placeholder="请输入分类名称" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item label="分类状态" prop="dataStatus">
          <el-select v-model="queryParams.dataStatus" placeholder="请选择分类状态" clearable size="small">
            <el-option v-for="dict in dataStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

        <el-form-item style="margin-left: 22px;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>

      </el-row>
    </el-form>

    <el-row class="row-mbinfo">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['product:group:add']">新增
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="divTable">
      <el-table border v-loading="loading" :data="groupList" row-key="groupUid"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column label="分类名称" align="center" prop="groupName" width="200px;">
          <template slot-scope="scope">
            <div class="show_cate_info">
              <span> {{scope.row.groupName}}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" prop="dataStatus" :formatter="dataStatusFormat">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.dataStatus" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="dataPriority" :show-overflow-tooltip="true" sortable />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180" sortable>
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['product:group:edit']">修改
            </el-button>
            <el-button v-if="scope.row.groupDepth != 2 " size="mini" type="text" icon="el-icon-plus"
              @click="handleAdd(scope.row)" v-hasPermi="['product:group:add']">新增</el-button>
            <el-button v-if="scope.row.dataStatus == '0'" size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(scope.row)" v-hasPermi="['product:group:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>
    <!-- 添加或修改商品分组信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @keyup.enter.native="submitForm"
      :destroy-on-close="true" @close="hahas" z-index="1000">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级分类" prop="parentGroupUid">
          <el-select v-model="form.parentGroupUid" placeholder="上级分类" clearable>
            <el-option v-for="cate in groupDepthList" :key="cate.groupUid" :label="cate.groupName"
              :value="cate.groupUid" class="input-rule" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分类名称" class="select-normal" maxlength="20" show-word-limit />
        </el-form-item>

        <el-form-item label="排序" prop="dataPriority">
          <el-input-number v-model="form.dataPriority" placeholder="请输入排序" controls-position="right" :min="0"
            class="select-normal" :max="999999" />
        </el-form-item>


        <!-- <el-form-item label="商品" prop="proUid">
          <el-button @click="selectCommodity">选择商品</el-button>
          <selected style="margin-top: 10px;" v-if="selectedData.length > 0" :selectedData="selectedData"></selected>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listGroup,
  getGroup,
  delGroup,
  addGroup,
  updateGroupStatus,
  updateGroup, listByType
} from "@/api/product/group";

import commoditytab from "@/components/Activity/commodityTab";
import selected from "@/components/Activity/SelectedProductsStatus";

import commodityItem from "@/components/Activity/commodityItem";
import SelectedItem from "@/components/Activity/SelectedItemStatus";

import commodityCard from "@/components/Activity/commodityCard";
import SelectedCard from "@/components/Activity/SelectedCardStatus";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: "Group",
  components: {
    commoditytab,
    selected, commodityItem, SelectedItem, commodityCard, SelectedCard
  },
  data () {
    return {
      componentGroupId: '',
      componentGroupType: '',
      ddlOpen: false,
      openDdlView: false,
      selectedDataDdl: [],

      selectedData: [],
      selectedDataCard: [],
      selectedDataItem: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      displayBool: 0,
      isShow: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品分组信息表格数据
      groupList: [],
      // 弹出层标题
      title: "",
      //查看详细标题
      viewTitle: "",
      // 是否显示弹出层
      open: false,
      proOpen: false,
      openView: false,
      openCardView: false,
      cardOpen: false,
      openItemView: false,
      itemOpen: false,
      // openView: false,
      //是否显示查看详细弹出层
      viewOpen: false,
      //查看详细数据
      showData: [],
      // 状态(1有效/0无效)字典
      dataStatusOptions: [],
      groupDepthList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: null,
      },
      groupUidOne: null,
      columns: [{
        label: '更新时间',
        dataIndex: 'groupUid',
      },
      {
        label: '平台ID',
        dataIndex: 'platformUid',
      },
      {
        label: '分类名称',
        dataIndex: 'groupName',
      },
      {
        label: '状态(1有效/0无效)',
        dataIndex: 'dataStatus',
      },
      {
        label: '排序',
        dataIndex: 'dataPriority',
      },
      {
        label: '创建人ID',
        dataIndex: 'createUid',
      },
      {
        label: '创建人名称',
        dataIndex: 'createName',
      },
      {
        label: '创建时间',
        dataIndex: 'createTime',
      },
      {
        label: '更新人ID',
        dataIndex: 'updateUid',
      },
      {
        label: '更新人名称',
        dataIndex: 'updateName',
      },
      {
        label: '更新时间',
        dataIndex: 'updateTime',
      },
      ],
      // 表单参数
      form: {
        serviceType: ""
      },
      // 表单校验
      rules: {

        groupName: [{
          required: true,
          message: "分类名称不能为空",
          trigger: "blur"
        }],
        dataPriority: [{
          required: true,
          message: "排序名称不能为空",
          trigger: "blur"
        }],
        parentGroupUid: [{
          required: true,
          message: "请选择上级分类",
          trigger: "change"
        }],
      },
      serviceTypesList: []
    };
  },
  created () {
    this.getList();
    this.getDicts("sys_data_status").then(response => {
      this.dataStatusOptions = response.data;
    });
    this.getDicts("item_apply_store_type").then(response => {
      this.serviceTypesList = response.data;
    });
  },
  methods: {
    choiceServiceCheckbox (value) {
      // this.selectedDataStore = []
      // this.selectedDataDevice = []
    },
    disabledType (value) {

      if (value == 'Probxplus') {
        return false;
      }
      // if (value != this.form.cardType) {
      //   return true;
      // }
    },
    multipleSelectionItem (data) {
      this.itemOpen = false
      this.selectedDataItem = data;
      this.$nextTick(() => {
        this.$refs.childss.getList();
      });
    },
    toCloseBoxItem () {
      this.itemOpen = false;
    },
    //调用子组件中方法，向子组件传值
    selectCommodityItem () {
      this.$forceUpdate()
      this.itemOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableItem"].greet(this.selectedDataItem);
      });
    },
    multipleSelectionCard (data) {
      this.cardOpen = false
      this.selectedDataCard = data;
      this.$nextTick(() => {
        this.$refs.childs.getList();
      });
    },
    toCloseBoxCard () {
      this.cardOpen = false;
    },
    //调用子组件中方法，向子组件传值
    selectCommodityCard () {
      this.$forceUpdate()
      this.cardOpen = true;
      this.$nextTick(() => {
        this.$refs["selTableCard"].greet(this.selectedDataCard);
      });
    },

    multipleSelection (data) {
      this.proOpen = false
      this.selectedData = data;
      this.$nextTick(() => {
        this.$refs.child.getList();
      });
    },
    toCloseBox () {
      this.proOpen = false;
    },
    //调用子组件中方法，向子组件传值
    selectCommodity () {
      this.$forceUpdate()
      this.proOpen = true;
      this.$nextTick(() => {
        this.$refs["selTable"].greet(this.selectedData);
      });
    },
    /** 查询商品分组信息列表 */
    getList () {
      this.loading = true;
      listGroup(this.queryParams).then(response => {
        this.groupList = this.handleTree(response.rows, "groupUid", "parentGroupUid");
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态(1有效/0无效)字典翻译
    dataStatusFormat (row, column) {
      return this.selectDictLabel(this.dataStatusOptions, row.dataStatus);
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancels () {
      this.openView = false;
    },
    cancelsCard () {
      this.openCardView = false;
    },
    cancelsItem () {
      this.openItemView = false;
    },
    // 表单重置
    reset () {
      this.form = {
        groupUid: null,
        platformUid: null,
        groupName: null,
        dataStatus: null,
        dataPriority: 10,
        createUid: null,
        createName: null,
        createTime: null,
        updateUid: null,
        updateName: null,
        updateTime: null,
        serviceType: null,
        groupDepthList:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.groupUid)
      this.names = selection.map(item => item.groupName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      //用于禁用删除
      if (this.multiple == false) {
        for (var i = 0; i < selection.length; i++) {
          var element = selection[i];
          if ("1" === element.dataStatus) {
            this.multiple = true;
            break;
          }
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset();
      this.open = true;
      this.title = "添加论文分类";
      this.proTableOpen = true;
      if (row != null && row.groupUid) {
        this.form.parentGroupUid = row.groupUid;
        this.form.groupDepth = row.groupDepth + 1;
        this.groupDepthList = [{
          groupName: row.groupName,
          groupUid: row.groupUid
        }];
      } else {
        this.groupDepthList = [{
          groupName: "顶级分类",
          groupUid: 0
        }];
        this.form.categoryDepth = 0;
      }
    },
    // 状态修改
    handleStatusChange (row) {
      let text = row.dataStatus === "0" ? "无效" : "有效";
      this.$confirm('确定要把分类名称为"' + row.groupName + '"设为' + text + '吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return updateGroupStatus(row.groupUid, row.dataStatus);
      }).then(() => {
        this.msgSuccess("操作成功");
        this.getList();
      }).catch(function () {
        row.dataStatus = row.dataStatus === "0" ? "1" : "0";
      });
    },
    handleCloseItem () {
      this.selectedDataItem = []
      this.openItemView = false;
    },
    handleGetItem (row) {
      this.reset();
      const groupUid = row.groupUid || this.ids
      listByType(groupUid, 'service').then(response => {
        // this.form = response.data;
        this.componentGroupId = groupUid + ''
        this.componentGroupType = 'service'
        this.selectedDataItem = response.data;
        this.openItemView = true;
        this.groupUidOne = row.groupUid;
      });
    },
    handleCloseCard () {
      this.selectedDataCard = []
      this.openCardView = false;
    },
    handleGetCard (row) {
      this.reset();
      const groupUid = row.groupUid || this.ids
      listByType(groupUid, 'card').then(response => {
        this.selectedDataCard = response.data;
        this.componentGroupId = groupUid + ''
        this.componentGroupType = 'card'
        this.openCardView = true;
        this.groupUidOne = row.groupUid;
      });
    },
    handleCloseProduct () {
      this.selectedData = []
      this.openView = false;
    },
    handleGet (row) {
      this.reset();
      const groupUid = row.groupUid || this.ids
      listByType(groupUid, 'product').then(response => {
        this.componentGroupId = groupUid + ''
        this.componentGroupType = 'product'
        this.selectedData = response.data;
        console.log(this.selectedData)
        this.openView = true;
        this.groupUidOne = row.groupUid;
      });
    },
    submitForms (type) {
      let qf = [];
      if (type == 'service') {
        this.selectedDataItem.forEach(vo => {
          let da = {};
          da.productUid = vo.itemId;
          da.isTuiJian = vo.isTuiJian
          qf.push(da)
          // qf.push(vo.itemId);
        })
      } else if (type == 'card') {

        this.selectedDataCard.forEach(vo => {
          let da = {};
          da.productUid = vo.cardId;
          da.isTuiJian = vo.isTuiJian
          qf.push(da)
        })
      } else {
        this.selectedData.forEach(vo => {
          let da = {};

          da.productUid = vo.productUid;
          da.isTuiJian = vo.isTuiJian
          qf.push(da)
        })
      }

      this.form.dataPriority = null
      this.form.serviceType = null
      this.form.productType = type
      this.form.productIdList = qf;
      this.form.groupUid = this.groupUidOne
      updateGroup(this.form).then(response => {
        this.msgSuccess("修改成功");
        if (type == 'service') {
          this.openItemView = false;
        } else if (type == 'card') {
          this.openCardView = false;
        } else {
          this.openView = false;
        }
        this.getList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const groupUid = row.groupUid || this.ids
      getGroup(groupUid).then(response => {
        this.form = response.data;

        this.selectedData = this.form.list;
        this.open = true;
        this.title = "修改论文分类信息";

        if (row != null && row.parentGroupUid==0) {
          this.groupDepthList = [{
            groupName: "顶级分类",
            groupUid: 0
          }];
        } else {

          getGroup(row.parentGroupUid).then(response => {
            let parent = response.data;
            this.groupDepthList = [{
              groupName: parent.groupName,
              groupUid: parent.groupUid
            }];
          });

        }

      });
    },
    /** 提交按钮 */
    submitForm () {
      let qf = [];
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.groupUid != null) {
            updateGroup(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGroup(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    hahas () {
      this.selectedData = [];
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const groupUids = row.groupUid || this.ids;
      const names = row.groupName || this.names;
      this.$confirm('是否确认删除论文分类名称为"' + names + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delGroup(groupUids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    }
  }
};
</script>
<style scoped="scoped">
.div-show {
  display: none;
}
</style>
<style scoped="scoped">
  .img-text {
    position: relative;
    /* top: -9px; */
  }
  .show_cate_info {
    display: flex;
    align-items: center;
  }
</style>
<style lang="scss">

    .el-table .cell {
      display: flex;
      align-items: left;
      justify-content: center;
    }

</style>
